import json
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
import streamlit as st
from datetime import datetime
import io

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False

DATA_FILE = 'contributions.json'

def load_data():
    try:
        with open(DATA_FILE, 'r', encoding='utf-8') as f:
            content = f.read().strip()
            if not content:
                return []
            return json.loads(content)
    except (FileNotFoundError, json.JSONDecodeError) as e:
        # If file doesn't exist or is corrupted, return empty list
        print(f"Warning: {e}. Starting with empty data.")
        return []

def save_data(data):
    with open(DATA_FILE, 'w', encoding='utf-8') as f:
        json.dump(data, f, ensure_ascii=False, indent=2)

def calculate_weighted_contribution(df):
    """计算带权重的个人贡献度"""
    # Only include completed tasks
    completed_tasks = df[df['完成情况'] == '已完成']
    
    if completed_tasks.empty:
        return pd.Series(dtype=float), pd.Series(dtype=float), pd.Series(dtype=float)
    
    # Calculate contributions by tag and person
    contribution_data = []
    
    for person in completed_tasks['姓名'].unique():
        person_tasks = completed_tasks[completed_tasks['姓名'] == person]
        
        # Count tasks by tag
        jixun_count = len(person_tasks[person_tasks['标签'] == '集训'])
        guosai_count = len(person_tasks[person_tasks['标签'] == '国赛'])
        
        # Calculate weighted contribution (集训 30%, 国赛 70%)
        weighted_score = jixun_count * 0.3 + guosai_count * 0.7
        
        contribution_data.append({
            'person': person,
            'jixun_count': jixun_count,
            'guosai_count': guosai_count,
            'weighted_score': weighted_score
        })
    
    contrib_df = pd.DataFrame(contribution_data)
    contrib_df = contrib_df.set_index('person')
    
    return contrib_df['jixun_count'], contrib_df['guosai_count'], contrib_df['weighted_score']

def generate_charts(df):
    # Only include tasks that have been started (exclude "未进行")
    started_tasks = df[df['完成情况'] != '未进行']
    completed = started_tasks[started_tasks['完成情况'] == '已完成'].groupby('姓名').size()
    total_completed = completed.sum()
    if total_completed == 0:
        return None, None, None, None
    proportions = completed / total_completed
    
    # 设置统一的图表大小和比例
    figsize = (10, 10)  # 固定长宽完全相同
    
    # Bar chart - 显示数量而非占比
    fig_bar, ax_bar = plt.subplots(figsize=figsize)
    completed.plot(kind='bar', ax=ax_bar)
    ax_bar.set_ylabel('完成任务数量')
    ax_bar.set_title('已完成任务数量 (柱状图)')
    # 确保y轴根据数据自动调整
    ax_bar.autoscale(axis='y')
    # 设置图表的长宽比例固定
    fig_bar.set_tight_layout(True)
    
    # Pie chart
    fig_pie, ax_pie = plt.subplots(figsize=figsize)
    proportions.plot(kind='pie', ax=ax_pie, autopct='%1.1f%%')
    ax_pie.set_title('已完成任务占比 (饼状图)')
    fig_pie.set_tight_layout(True)
    
    # Tag distribution charts - 包含已完成、进行中和未完成的任务
    active_tasks = df[df['完成情况'].isin(['已完成', '进行中', '未完成'])]
    if not active_tasks.empty and '标签' in active_tasks.columns:
        # Tag distribution pie chart
        tag_counts = active_tasks['标签'].value_counts()
        fig_tag_pie, ax_tag_pie = plt.subplots(figsize=figsize)
        tag_counts.plot(kind='pie', ax=ax_tag_pie, autopct='%1.1f%%')
        ax_tag_pie.set_title('集训/国赛任务占比 ')
        fig_tag_pie.set_tight_layout(True)
        
        # Weighted contribution chart
        jixun_counts, guosai_counts, weighted_scores = calculate_weighted_contribution(df)
        if not weighted_scores.empty:
            fig_weighted, ax_weighted = plt.subplots(figsize=figsize)
            weighted_scores.plot(kind='bar', ax=ax_weighted)
            ax_weighted.set_ylabel('加权贡献度')
            ax_weighted.set_title('个人加权贡献度 (集训30% + 国赛70%)')
            ax_weighted.tick_params(axis='x', rotation=45)
            # 确保y轴根据数据自动调整
            ax_weighted.autoscale(axis='y')
            fig_weighted.set_tight_layout(True)
            return fig_bar, fig_pie, fig_tag_pie, fig_weighted
    
    return fig_bar, fig_pie, None, None

# Streamlit app
st.title('🎯 贡献度管理系统')

# Load data
data = load_data()

# Assign IDs to existing data
if data:
    existing_ids = [row.get('编号', 0) for row in data if row.get('编号')]
    max_id = max(existing_ids) if existing_ids else 0
else:
    max_id = 0
for row in data:
    if '编号' not in row or not row['编号']:
        max_id += 1
        row['编号'] = max_id

# Convert to DataFrame
df_data = pd.DataFrame(data)
if not df_data.empty:
    df_data['日期'] = pd.to_datetime(df_data['日期'], errors='coerce')
    # Add 标签 column if it doesn't exist
    if '标签' not in df_data.columns:
        df_data['标签'] = '集训'  # Default to 集训 for existing data
    # Reorder columns to put 编号 first
    column_order = ['编号', '姓名', '任务', '日期', '标签', '完成情况']
    df_data = df_data.reindex(columns=column_order)
else:
    df_data = pd.DataFrame(columns=['编号', '姓名', '任务', '日期', '标签', '完成情况'])

# Create tabs for different views
tab1, tab2, tab3 = st.tabs(["📊 数据展示", "✏️ 数据录入", "📈 统计分析"])

# Tab 1: Data Display (观看者体验)
with tab1:
    st.header("📋 任务完成情况一览")
    
    if not df_data.empty:
        # Filter out empty rows for display
        valid_rows = df_data.dropna(subset=['姓名'])
        
        if not valid_rows.empty:
            # === 筛选和排序控件 ===
            st.subheader("🔍 筛选和排序")
            
            # Create filter columns
            filter_col1, filter_col2, filter_col3, filter_col4 = st.columns(4)
            
            with filter_col1:
                # 姓名筛选
                all_names = ['全部'] + sorted(valid_rows['姓名'].dropna().unique().tolist())
                selected_name = st.selectbox("👤 按姓名筛选", all_names, key="display_name_filter")
            
            with filter_col2:
                # 完成情况筛选
                all_status = ['全部'] + valid_rows['完成情况'].unique().tolist()
                selected_status = st.selectbox("📋 按完成情况筛选", all_status, key="display_status_filter")
            
            with filter_col3:
                # 标签筛选
                all_tags = ['全部'] + valid_rows['标签'].unique().tolist()
                selected_tag = st.selectbox("🏷️ 按标签筛选", all_tags, key="display_tag_filter")
            
            with filter_col4:
                # 排序选项
                sort_options = {
                    '编号 (升序)': ('编号', True),
                    '编号 (降序)': ('编号', False),
                    '姓名 (A-Z)': ('姓名', True),
                    '姓名 (Z-A)': ('姓名', False),
                    '日期 (最新)': ('日期', False),
                    '日期 (最早)': ('日期', True)
                }
                selected_sort = st.selectbox("📊 排序方式", list(sort_options.keys()), key="display_sort")
            
            # 日期范围筛选
            date_col1, date_col2 = st.columns(2)
            with date_col1:
                start_date = st.date_input("📅 开始日期", value=None, key="display_start_date")
            with date_col2:
                end_date = st.date_input("📅 结束日期", value=None, key="display_end_date")
            
            # 应用筛选
            filtered_data = valid_rows.copy()
            
            # 姓名筛选
            if selected_name != '全部':
                filtered_data = filtered_data[filtered_data['姓名'] == selected_name]
            
            # 完成情况筛选
            if selected_status != '全部':
                filtered_data = filtered_data[filtered_data['完成情况'] == selected_status]
            
            # 标签筛选
            if selected_tag != '全部':
                filtered_data = filtered_data[filtered_data['标签'] == selected_tag]
            
            # 日期范围筛选
            if start_date:
                filtered_data = filtered_data[filtered_data['日期'] >= pd.Timestamp(start_date)]
            if end_date:
                filtered_data = filtered_data[filtered_data['日期'] <= pd.Timestamp(end_date)]
            
            # 应用排序
            sort_column, ascending = sort_options[selected_sort]
            if sort_column in filtered_data.columns:
                filtered_data = filtered_data.sort_values(sort_column, ascending=ascending)
            
            st.divider()
            
            # === 统计信息 ===
            if not filtered_data.empty:
                # Filter out "未进行" tasks for statistics - only count tasks that have been started
                started_tasks = filtered_data[filtered_data['完成情况'] != '未进行']
                
                # Quick stats at the top
                col1, col2, col3, col4, col5, col6 = st.columns(6)
                # 更新统计逻辑，包括进行中状态
                started_tasks = filtered_data[filtered_data['完成情况'].isin(['进行中', '未完成', '已完成'])]
                completed_count = len(started_tasks[started_tasks['完成情况'] == '已完成'])
                incomplete_count = len(started_tasks[started_tasks['完成情况'] == '未完成'])
                progress_count = len(started_tasks[started_tasks['完成情况'] == '进行中'])
                not_started_count = len(filtered_data[filtered_data['完成情况'] == '未进行'])
                started_count = len(started_tasks)
                total_count = len(filtered_data)
                completion_rate = (completed_count / started_count * 100) if started_count > 0 else 0
                
                # 更新统计指标显示，添加进行中计数
                with col1:
                    st.metric("📋 总任务", total_count)
                with col2:
                    st.metric("🚀 已进行", started_count, help="已开始的任务数量")
                with col3:
                    st.metric("✅ 已完成", completed_count)
                with col4:
                    st.metric("❌ 未完成", incomplete_count)
                with col5:
                    st.metric("🔄 进行中", progress_count)
                with col6:
                    st.metric("📊 完成率", f"{completion_rate:.1f}%", help="已完成任务占已进行任务的比例")
                
                # Tag statistics
                if '标签' in filtered_data.columns:
                    completed_tasks = filtered_data[filtered_data['完成情况'] == '已完成']
                    if not completed_tasks.empty:
                        st.divider()
                        st.subheader("🏷️ 标签统计")
                        col1, col2, col3 = st.columns(3)
                        
                        jixun_count = len(completed_tasks[completed_tasks['标签'] == '集训'])
                        guosai_count = len(completed_tasks[completed_tasks['标签'] == '国赛'])
                        
                        with col1:
                            st.metric("🎯 集训任务", jixun_count)
                        with col2:
                            st.metric("🏆 国赛任务", guosai_count)
                        with col3:
                            # Calculate weighted contribution for display
                            total_weighted = jixun_count * 0.3 + guosai_count * 0.7
                            st.metric("⚖️ 加权总分", f"{total_weighted:.1f}", help="集训任务×0.3 + 国赛任务×0.7")
                
                # Additional info
                if not_started_count > 0:
                    st.info(f"⏸️ 有 {not_started_count} 个任务尚未开始，不计入完成率统计")
                
                st.divider()
                
                # === 任务详情表格 ===
                st.subheader("🎯 任务详情")
                
                # 显示筛选结果数量
                st.info(f"📊 当前显示 {len(filtered_data)} 条记录")
                
                # 详细视图 - Group by person for better organization
                for person in filtered_data['姓名'].unique():
                    if pd.notna(person):
                        person_tasks = filtered_data[filtered_data['姓名'] == person]
                        
                        with st.expander(f"👤 {person} ({len(person_tasks)} 个任务)", expanded=False):
                            # 添加表头
                            header_col1, header_col2, header_col3, header_col4, header_col5 = st.columns([0.8, 4.5, 1.5, 1.2, 1.2])
                            with header_col1:
                                st.markdown("**编号**")
                            with header_col2:
                                st.markdown("**任务内容**")
                            with header_col3:
                                st.markdown("**日期**")
                            with header_col4:
                                st.markdown("**标签**")
                            with header_col5:
                                st.markdown("**状态**")
                            
                            st.markdown("---")
                            
                            for idx, task in person_tasks.iterrows():
                                # 使用容器来确保一致的间距
                                task_container = st.container()
                                with task_container:
                                    col1, col2, col3, col4, col5 = st.columns([0.8, 4.5, 1.5, 1.2, 1.2])
                                    
                                    with col1:
                                        st.markdown(f"<div style='padding: 8px 0; font-weight: bold; color: #666;'>#{task['编号']}</div>", unsafe_allow_html=True)
                                    
                                    with col2:
                                        st.markdown(f"<div style='padding: 8px 0; font-weight: 500; line-height: 1.4;'>{task['任务']}</div>", unsafe_allow_html=True)
                                    
                                    with col3:
                                        date_str = task['日期'].strftime('%m-%d') if pd.notnull(task['日期']) else '未设置'
                                        st.markdown(f"<div style='padding: 8px 0; white-space: nowrap; font-size: 14px;'>📅 {date_str}</div>", unsafe_allow_html=True)
                                    
                                    with col4:
                                        # Display tag with appropriate emoji
                                        tag = task.get('标签', '集训')
                                        if tag == '集训':
                                            st.markdown('<div style="background-color: #e3f2fd; color: #1976d2; padding: 6px 8px; border-radius: 4px; text-align: center; font-size: 12px; margin: 4px 0; white-space: nowrap;">🎯 集训</div>', unsafe_allow_html=True)
                                        else:  # 国赛
                                            st.markdown('<div style="background-color: #fff3e0; color: #f57c00; padding: 6px 8px; border-radius: 4px; text-align: center; font-size: 12px; margin: 4px 0; white-space: nowrap;">🏆 国赛</div>', unsafe_allow_html=True)
                                    
                                    with col5:
                                        # 更新详细视图中完成情况的显示，添加进行中
                                        if task['完成情况'] == '已完成':
                                            st.markdown('<div style="background-color: #d4edda; color: #155724; padding: 6px 8px; border-radius: 4px; text-align: center; font-weight: bold; font-size: 12px; margin: 4px 0; white-space: nowrap;">✅ 已完成</div>', unsafe_allow_html=True)
                                        elif task['完成情况'] == '未完成':
                                            st.markdown('<div style="background-color: #f8d7da; color: #721c24; padding: 6px 8px; border-radius: 4px; text-align: center; font-weight: bold; font-size: 12px; margin: 4px 0; white-space: nowrap;">❌ 未完成</div>', unsafe_allow_html=True)
                                        elif task['完成情况'] == '进行中':
                                            st.markdown('<div style="background-color: #fff3cd; color: #856404; padding: 6px 8px; border-radius: 4px; text-align: center; font-weight: bold; font-size: 12px; margin: 4px 0; white-space: nowrap;">🔄 进行中</div>', unsafe_allow_html=True)
                                        else:  # 未进行
                                            st.markdown('<div style="background-color: #e2e3e5; color: #6c757d; padding: 6px 8px; border-radius: 4px; text-align: center; font-weight: bold; font-size: 12px; margin: 4px 0; white-space: nowrap;">⏸️ 未进行</div>', unsafe_allow_html=True)
                                
                                # 添加分隔线（除了最后一行）
                                if idx != person_tasks.index[-1]:
                                    st.markdown('<div style="border-bottom: 1px solid #f0f0f0; margin: 8px 0;"></div>', unsafe_allow_html=True)
            else:
                st.warning("🔍 没有符合筛选条件的数据")
        else:
            st.info("📝 暂无任务数据，请在'数据录入'标签页添加任务")
    else:
        st.info("📝 暂无任务数据，请在'数据录入'标签页添加任务")

# Tab 2: Data Input (输入者体验)
with tab2:
    st.header("✏️ 任务数据录入")
    
    # 初始化显示空行的控制变量
    show_empty_rows = True
    
    # === 筛选和编辑控件 ===
    if not df_data.empty:
        valid_input_data = df_data.dropna(subset=['姓名'])
        if not valid_input_data.empty:
            st.subheader("🔍 筛选编辑数据")
            
            # Create filter columns for input tab
            input_filter_col1, input_filter_col2, input_filter_col3, input_filter_col4 = st.columns(4)
            
            with input_filter_col1:
                # 姓名筛选
                all_names_input = ['全部'] + sorted(valid_input_data['姓名'].unique().tolist())
                selected_name_input = st.selectbox("👤 筛选编辑对象", all_names_input, key="input_name_filter")
            
            with input_filter_col2:
                # 完成情况筛选
                all_status_input = ['全部'] + valid_input_data['完成情况'].unique().tolist()
                selected_status_input = st.selectbox("📋 筛选完成情况", all_status_input, key="input_status_filter")
            
            with input_filter_col3:
                # 标签筛选
                all_tags_input = ['全部'] + valid_input_data['标签'].unique().tolist()
                selected_tag_input = st.selectbox("🏷️ 筛选标签", all_tags_input, key="input_tag_filter")
            
            with input_filter_col4:
                # 显示行数控制
                show_empty_rows = st.checkbox("显示空行用于新增", value=True, key="show_empty_rows")
            
            st.divider()
    
    # Data editor for input
    st.subheader('📝 编辑任务数据')
    
    # Auto-assign IDs for new rows in the editor
    if not df_data.empty:
        current_max_id = df_data['编号'].max(skipna=True)
        if pd.isna(current_max_id):
            current_max_id = 0
    else:
        current_max_id = 0

    # 准备编辑数据
    edit_data = df_data.copy()
    
    # 应用筛选（如果有数据的话）
    if not df_data.empty and 'selected_name_input' in locals():
        valid_edit_data = edit_data.dropna(subset=['姓名'])
        
        if not valid_edit_data.empty:
            # 应用筛选条件
            if selected_name_input != '全部':
                valid_edit_data = valid_edit_data[valid_edit_data['姓名'] == selected_name_input]
            
            if selected_status_input != '全部':
                valid_edit_data = valid_edit_data[valid_edit_data['完成情况'] == selected_status_input]
            
            if selected_tag_input != '全部':
                valid_edit_data = valid_edit_data[valid_edit_data['标签'] == selected_tag_input]
            
            # 重新组合数据：筛选后的有效数据
            edit_data = valid_edit_data.copy()
            
            # 显示筛选结果信息
            if not edit_data.empty:
                st.info(f"📊 当前筛选显示 {len(edit_data)} 条记录用于编辑")
            else:
                st.warning("🔍 没有符合筛选条件的数据")

    # Add empty rows with auto-assigned IDs for editing
    if show_empty_rows or edit_data.empty:
        num_empty_rows = 5  # Add 5 empty rows for new entries
        for i in range(num_empty_rows):
            current_max_id += 1
            new_row = {'编号': current_max_id, '姓名': None, '任务': None, '日期': None, '标签': '集训', '完成情况': '未进行'}
            edit_data = pd.concat([edit_data, pd.DataFrame([new_row])], ignore_index=True)

    # Ensure column order is maintained
    column_order = ['编号', '姓名', '任务', '日期', '标签', '完成情况']
    edit_data = edit_data.reindex(columns=column_order)

    # 在数据编辑器中更新完成情况选项
    edited_df = st.data_editor(
        edit_data,
        num_rows='dynamic',
        column_config={
            '编号': st.column_config.NumberColumn('编号', disabled=True, required=True),
            '姓名': st.column_config.TextColumn('姓名', help="输入负责人姓名"),
            '任务': st.column_config.TextColumn('任务', help="输入具体任务内容"),
            '日期': st.column_config.DateColumn('日期', format='YYYY-MM-DD', help="选择任务日期"),
            '标签': st.column_config.SelectboxColumn(
                '标签', 
                options=['集训', '国赛'], 
                default='集训', 
                required=True,
                help="选择任务类型：集训-日常训练任务(权重30%)，国赛-国赛相关任务(权重70%)"
            ),
            '完成情况': st.column_config.SelectboxColumn(
                '完成情况', 
                options=['未进行', '进行中', '未完成', '已完成'], 
                default='未进行', 
                required=True,
                help="选择任务完成状态：未进行-任务尚未开始，进行中-任务正在进行，未完成-任务未完成，已完成-任务已完成"
            )
        },
        hide_index=True,
        use_container_width=True
    )
    
    # Action buttons
    col1, col2, col3 = st.columns(3)
    
    with col1:
        if st.button('💾 保存数据', type="primary", use_container_width=True):
            # Convert to list of dicts
            new_data = edited_df.to_dict('records')
            # Remove rows that are completely empty (all values are NaN except 编号)
            filtered_data = []
            for row in new_data:
                # Check if row has meaningful data (not just 编号)
                has_data = any(pd.notnull(v) and v != '' for k, v in row.items() if k != '编号')
                if has_data:
                    filtered_data.append(row)
            
            # Reassign continuous IDs to filtered data
            for i, row in enumerate(filtered_data, 1):
                row['编号'] = i
            
            # Clean up data for JSON serialization
            for row in filtered_data:
                # Handle date conversion
                if '日期' in row and pd.notnull(row['日期']):
                    try:
                        dt = pd.to_datetime(row['日期'])
                        if pd.notnull(dt):
                            row['日期'] = dt.strftime('%Y-%m-%d')
                        else:
                            row['日期'] = None
                    except:
                        row['日期'] = None
                
                # Set default values for new columns
                if '标签' not in row or pd.isna(row['标签']) or row['标签'] == '':
                    row['标签'] = '集训'
                
                # Clean up all values for JSON compatibility
                for key in row:
                    value = row[key]
                    if pd.isna(value) or value is pd.NaT:
                        row[key] = None
                    elif isinstance(value, (pd.Timestamp, datetime)):
                        row[key] = value.strftime('%Y-%m-%d') if key == '日期' else str(value)
                    elif isinstance(value, (int, float)) and pd.isna(value):
                        row[key] = None
                    elif value == '':
                        row[key] = None
            
            save_data(filtered_data)
            st.success('✅ 数据已保存成功！')
            # Refresh the page to show updated data
            st.rerun()
    
    with col2:
        # Excel export
        if st.button('📤 导出Excel', use_container_width=True):
            output = io.BytesIO()
            with pd.ExcelWriter(output, engine='openpyxl') as writer:
                edited_df.to_excel(writer, index=False)
            st.download_button(
                label='⬇️ 下载Excel文件', 
                data=output.getvalue(), 
                file_name='contributions.xlsx', 
                mime='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                use_container_width=True
            )
    
    with col3:
        # Excel import
        uploaded_file = st.file_uploader('📥 导入Excel文件', type=['xlsx'])
        if uploaded_file:
            df_uploaded = pd.read_excel(uploaded_file)
            
            # Get current max ID from existing local data
            existing_data = load_data()
            if existing_data:
                existing_ids = [row.get('编号', 0) for row in existing_data if row.get('编号')]
                current_max_id = max(existing_ids) if existing_ids else 0
            else:
                current_max_id = 0
            
            # Process uploaded data - ignore 编号 column from Excel
            import_columns = ['姓名', '任务', '日期', '标签', '完成情况']
            df_import = df_uploaded[[col for col in import_columns if col in df_uploaded.columns]]
            
            # Convert to dict and assign new IDs based on local data
            imported_records = df_import.to_dict('records')
            
            # Function to check if a record already exists (based on 姓名, 任务, 日期, 标签, 完成情况)
            def record_exists(new_record, existing_records):
                for existing in existing_records:
                    if (existing.get('姓名') == new_record.get('姓名') and
                        existing.get('任务') == new_record.get('任务') and
                        existing.get('日期') == new_record.get('日期') and
                        existing.get('标签') == new_record.get('标签') and
                        existing.get('完成情况') == new_record.get('完成情况')):
                        return True
                return False
            
            # Combine existing data with new imported data (avoid duplicates)
            combined_data = existing_data.copy()
            new_records_count = 0
            duplicate_count = 0
            
            for record in imported_records:
                # Skip empty rows
                has_data = any(pd.notnull(v) and v != '' for v in record.values())
                if has_data:
                    # Handle date conversion for comparison
                    if '日期' in record and pd.notnull(record['日期']):
                        try:
                            dt = pd.to_datetime(record['日期'])
                            if pd.notnull(dt):
                                record['日期'] = dt.strftime('%Y-%m-%d')
                            else:
                                record['日期'] = None
                        except:
                            record['日期'] = None
                    
                    # Check for duplicates
                    if not record_exists(record, existing_data):
                        current_max_id += 1
                        record['编号'] = current_max_id
                        
                        # Set default values if not provided
                        if '标签' not in record or pd.isna(record['标签']) or record['标签'] == '':
                            record['标签'] = '集训'
                        if '完成情况' not in record or pd.isna(record['完成情况']) or record['完成情况'] == '':
                            record['完成情况'] = '未进行'
                        
                        # Clean up values for JSON compatibility
                        for key in record:
                            value = record[key]
                            if pd.isna(value) or value == '':
                                record[key] = None
                        
                        combined_data.append(record)
                        new_records_count += 1
                    else:
                        duplicate_count += 1
            
            save_data(combined_data)
            
            # Show import results
            if new_records_count > 0:
                st.success(f'✅ 数据导入成功！共导入 {new_records_count} 条新记录')
                if duplicate_count > 0:
                    st.info(f'ℹ️ 跳过了 {duplicate_count} 条重复记录')
            else:
                st.warning('⚠️ 没有导入新数据，所有记录都已存在')
            
            st.rerun()

# Tab 3: Statistics and Charts (统计分析)
with tab3:
    st.header("📈 统计分析")
    
    # Display charts
    st.subheader('📊 完成情况图表')
    fig_bar, fig_pie, fig_tag_pie, fig_weighted = generate_charts(df_data)
    
    if fig_bar and fig_pie:
        col1, col2 = st.columns(2)
        with col1:
            st.pyplot(fig_bar)
        with col2:
            st.pyplot(fig_pie)
        
        # Display tag-related charts if available
        if fig_tag_pie and fig_weighted:
            st.divider()
            st.subheader('🏷️ 标签分析与加权贡献度')
            
            col1, col2 = st.columns(2)
            with col1:
                st.pyplot(fig_tag_pie)
            with col2:
                st.pyplot(fig_weighted)
            
            # Display detailed weighted contribution table
            st.subheader('📋 个人加权贡献度详情')
            completed_tasks = df_data[df_data['完成情况'] == '已完成']
            if not completed_tasks.empty:
                jixun_counts, guosai_counts, weighted_scores = calculate_weighted_contribution(df_data)
                
                if not weighted_scores.empty:
                    contrib_table = pd.DataFrame({
                        '姓名': weighted_scores.index,
                        '集训任务数': jixun_counts.values,
                        '国赛任务数': guosai_counts.values,
                        '加权得分': weighted_scores.values,
                        '贡献占比': (weighted_scores / weighted_scores.sum() * 100).round(1)
                    })
                    contrib_table = contrib_table.sort_values('加权得分', ascending=False)
                    
                    st.dataframe(
                        contrib_table,
                        column_config={
                            '姓名': st.column_config.TextColumn('姓名'),
                            '集训任务数': st.column_config.NumberColumn('集训任务数', help="权重: 30%"),
                            '国赛任务数': st.column_config.NumberColumn('国赛任务数', help="权重: 70%"),
                            '加权得分': st.column_config.NumberColumn('加权得分', format="%.1f", help="集训×0.3 + 国赛×0.7"),
                            '贡献占比': st.column_config.NumberColumn('贡献占比(%)', format="%.1f%%")
                        },
                        hide_index=True,
                        use_container_width=True
                    )
                    
                    # Show calculation formula
                    st.info("💡 **计算公式**: 加权得分 = 集训任务数 × 0.3 + 国赛任务数 × 0.7")
    else:
        st.info('📝 暂无完成数据，请先在"数据录入"页面登记一些记录。')